from django.core.files.storage import Storage
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response


class FastDFSStorage(Storage):
    # 重写django中的Storage的url方法,拼接我们自己想要的url
    def __init__(self, fdfs_base_url=None):
        self.fdfs_base_url = fdfs_base_url or settings.FDFS_BASE_URL

    def _save(self, name, content, max_length=None):
        conn = Fdfs_client(settings.FDFS_CONF_PATH)
        res = content.upload_by_buffer(content.read())
        if res:
            image_id = res['Remote file_id']
            return image_id
        raise serializers.ValidationError('文件上传失败')

    def url(self, name):
        return self.fdfs_base_url + name

    def exists(self, name):
        return False


def FastUploadImage(content):
    '''
    上传图片至fastdfs
    :param content: 图片对象
    :return: 字典类型
    # 如果上传失败
    if res['Status'] != 'Upload successed.':
        return HttpResponse(status=403)
    # FastDFS返回图片标识
    image_url = res["Remote file_id"]
    '''
    # 创建Fdfs客户端
    client = Fdfs_client(settings.FDFS_CONF_PATH)
    # 获取图片数据
    image_data = content.read()
    # 上传
    res = client.upload_by_buffer(image_data)
    return res


class UploadCommentImage(APIView):
    def post(self, request):
        image_data = self.request.FILES.get('img')
        res = FastUploadImage(image_data)
        if res['Status'] != 'Upload successed.':
            return Response({
                'message': '上传失败',
                'success': "false"
            })
        image_url = settings.FDFS_BASE_URL + res["Remote file_id"]
        return Response({'imgurl': image_url})